import { observer } from 'mobx-react-lite'
import { useEffect, useState } from 'react'
import { authStore } from '@renderer/store/user'
import styles from './index.module.less'

const Home: React.FC = observer(() => {
  const [newUsername, setNewUsername] = useState('')

  useEffect(() => {
    const cleanup = window.electronAPI?.on('username-updated', () => {
      authStore.loadUserFromStorage()
    })
    return () => {
      // cleanup?.()
    }
  }, [])

  const handleUpdateUsername = () => {
    if (newUsername.trim()) {
      authStore.updateUsername(newUsername)
      window.electronAPI?.broadcast('username-updated')
      setNewUsername('')
    }
  }

  const handleLogout = () => {
    authStore.logout()
  }

  return (
    <div className="home-container">
      <h1>Welcome, {authStore.user?.username}!</h1>
      <p>User ID: {authStore.user?.id}</p>

      <div className="update-section">
        <h2>Update Username</h2>
        <input
          type="text"
          value={newUsername}
          onChange={(e) => setNewUsername(e.target.value)}
          placeholder="New username"
          className="username-input"
        />
        <button onClick={handleUpdateUsername} className="update-btn">
          Update
        </button>
      </div>

      <button onClick={handleLogout} className="logout-btn">
        Logout
      </button>
    </div>
  )
})

export default Home
